﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;

namespace Linxiao.CRM.Plugin.RecordIDLookupInWorkflow
{
    public class Plugin: IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                //Get plugin execution context service
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                if (context.InputParameters["Target"] != null)
                {
                    //Get current record
                    Entity record = (Entity)context.InputParameters["Target"];
                    //Set custom RecordID field with the Guid of current record
                    record["new_recordid"] = record.Id.ToString();

                    //Commit in the change 
                    IOrganizationServiceFactory serviceFactory =(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service =serviceFactory.CreateOrganizationService(context.UserId);
                    service.Update(record);
                }
                else
                { 
                    //Log
                }
                
            }
            catch (Exception ex)
            {
                //Log Exception
            }
        }

    }
}
